package io.jnet.server.accepthandler;

import java.io.IOException;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import io.jnet.server.api.AcceptHandler;
import io.jnet.server.api.ServerChannelContext;
import io.jnet.server.api.ServerChannelContextBuilder;
import io.jnet.server.api.ServerListener;
import io.jnet.server.serverchannelcontext.SimpleServerChannelContext;
import io.jnet.server.util.ServerChannelContextConfig;

public class SimpleAcceptHandler implements AcceptHandler
{
    private ServerChannelContextBuilder     channelContextBuilder;
    private AsynchronousServerSocketChannel serverSocketChannel;
    private ServerListener                  serverListener;
    
    public SimpleAcceptHandler(AsynchronousServerSocketChannel serverSocketChannel, ServerChannelContextBuilder channelContextBuilder, ServerListener serverListener)
    {
        this.channelContextBuilder = channelContextBuilder;
        this.serverSocketChannel = serverSocketChannel;
        this.serverListener = serverListener;
    }
    
    @Override
    public void completed(AsynchronousSocketChannel socketChannel, Object attachment)
    {
        ServerChannelContextConfig config = channelContextBuilder.onConnect(socketChannel);
        ServerChannelContext serverChannelContext = parse(socketChannel, config);
        channelContextBuilder.afterContextBuild(serverChannelContext);
        serverChannelContext.registerRead();
        serverSocketChannel.accept(null, this);
    }
    
    private ServerChannelContext parse(AsynchronousSocketChannel socketChannel, ServerChannelContextConfig config)
    {
        ServerChannelContext serverChannelContext = new SimpleServerChannelContext(//
                config.getBufStorage(), //
                config.getMaxMerge(), //
                serverListener, //
                config.getProcessors(), //
                socketChannel, //
                config.getFrameDecodec());
        return serverChannelContext;
    }
    
    @Override
    public void failed(Throwable exc, Object attachment)
    {
        try
        {
            serverSocketChannel.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void stop()
    {
        ;
    }
    
}
